<?php

namespace app\common\model;


use think\Exception;

class MallSpecsValue extends TimeModel
{

    protected $name = "mall_specs_value";

    protected $deleteTime = "delete_time";


    public function getStatusList()
    {
        return ['0' => '禁用', '1' => '启用',];
    }

    /**
     * 查询所有规格
     * @param array $ids
     * @return array|string
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getSpecsValueByIdValue(array $ids = [])
    {
        $row = $this
            ->field("id,specs_id,title")
            ->where('id', 'in', $ids)
            ->select()
            ->toArray();
        if (empty($row)) {
            return "-";
        }
        //获取所有规格
        $specs_ids = array_column($row, "specs_id");
        if (empty($specs_ids)) {
            return "-";
        }
        try {
            $specs = (new MallSpecs())->getSpecsByIdsValue($specs_ids);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if (empty($specs)) {
            return "-";
        }
        $specs_value = [];
        foreach ($specs as $v) {
            $specs_value[$v['id']] = $v;
        }
        $lists = [];
        foreach ($row as $k => $value) {
            $lists[$k] = $value;
            $lists[$k]['value'] = $specs_value[$value['specs_id']]['title'] . ":" . $value['title'];
        }
        return $lists;

    }

    /**
     * @param array $ids
     * @param $with
     * @return array
     * @throws Exception
     */
    public function getSpecsValueByList(array $ids = [], $with = null): array
    {
        if (empty($ids)) {
            return [];
        }
        try {
            $row = $this
                ->field("id,specs_id,title")
                ->where('id', 'in', $ids)
                ->with($with)
                ->select()
                ->toArray();
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        return $row;

    }

    /**
     * @return \think\model\relation\HasOne
     */
    public function specs()
    {
        return $this->hasOne(MallSpecs::class, 'id', 'specs_id');
    }

}